package csc.daonjpa.java.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import share.Constant;

public class SessionTimeOutInterceptor extends HandlerInterceptorAdapter{
	@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Long customerId = (Long) request.getSession().getAttribute(Constant.SESSION_ATR_CUSTOMER_ID);
        Boolean isCustomer = (Boolean) request.getSession().getAttribute(Constant.SESSION_ATR_IS_CUSTOMER);
        
		if( !url.contains("images") && !url.contains("login") &&
			    !url.endsWith("/logout") && !url.contains("js") && !url.contains("css") && !url.contains("fonts")){
			if(customerId == null) {
				response.sendRedirect("login");
				return false;
			} else if (url.contains("admin") && (isCustomer == null || (isCustomer.compareTo(true) == 0))) {
				response.sendRedirect("login");					
				return false;
			} 
		 } else return true;
		//this is an admin and he want to access his pages
		if (isCustomer != null && url.contains("admin") && (isCustomer.compareTo(false) == 0)) {
			return true;
		}
		//this is a customer want to access admin page
		if (isCustomer != null && url.contains("admin") && (isCustomer.compareTo(true) == 0)) {
			response.sendRedirect("adminlogin");					
			return false;
		}
		//an admin want to access customer page
		if (isCustomer != null && !url.contains("admin") && (isCustomer.compareTo(false) == 0)) {
			response.sendRedirect("login");
			return false;
		}
		if (isCustomer != null && url.contains("login") && (isCustomer.compareTo(true) == 0)) {
			response.sendRedirect("home");
			return false;
		}
		
		return true;		
    }
}
